package com.kwan.x_im.data;

import android.app.Application;


import com.jeremyliao.liveeventbus.LiveEventBus;
import com.kwan.x_im.App;
import com.kwan.x_im.data.http.ApiService;
import com.kwan.x_im.data.http.HttpEvent;
import com.kwan.xframe.mvvm.data.source.http.HttpResult;
import com.kwan.xframe.mvvm.data.source.http.exception.HttpApiException;

import com.kwan.xframe.view_model.BaseViewModel;

import androidx.annotation.NonNull;
import io.reactivex.rxjava3.subscribers.DisposableSubscriber;
import timber.log.Timber;


/**
 * @author kwan
 * @date 2023/2/16 17:37
 * @Describe 其他 业务ViewMode 都应继承此类
 */
public class IMViewMode extends BaseViewModel {

	public IMViewMode(@NonNull Application application) {
		super(application);
		//DataManager.getInstance().getBaseTokenManager().setCacheToken("");
	}

	public static final int CODE_SUCCESS = 200;


	/*
	 *做一些统一的 回调返回逻辑处理，错误处理
	 */

	public <T> DisposableSubscriber<HttpResult<T>> getHttpCallBack(ApiService.FUNC func) {
		return new DisposableSubscriber<HttpResult<T>>() {
			@Override
			public void onNext(HttpResult<T> result) {
				if (result.getCode() == CODE_SUCCESS) {
					LiveEventBus
							.get(HttpEvent.class)
							.post(new HttpEvent<>(true, result, func));
				} else if (result.getCode() == 30004 || result.getCode() == 30003 || result.getCode() == 30005) {
					//out();
					//throw new TokenNotValidThrowable("服务器无效token");
				} else {
					LiveEventBus
							.get(HttpEvent.class)
							.post(new HttpEvent<>(false, result, func));
				}

				func.extra.clear();
			}

			@Override
			public void onError(Throwable throwable) {
				Timber.e("onError:%s", throwable);
				HttpResult<Object> result = new HttpResult<>();
				result.setMessage(throwable.getMessage());
				if (throwable instanceof HttpApiException) {
					HttpApiException e = (HttpApiException) throwable;
					result.setCode(e.getCode());
					if (e.getCode() == 30004 || e.getCode() == 30003 || e.getCode() == 30005) {
						//token 过期 需要退出重新登录
						//out();
						return;
					}
				}

				LiveEventBus
						.get(HttpEvent.class)
						.post(new HttpEvent<>(false, result, func));
				throwable.printStackTrace();
				func.extra.clear();

			}

			@Override
			public void onComplete() {

			}
		};
	}




}
